import React, { useEffect, useRef, useState, useCallback } from 'react';
import {
  Box,
  IconButton,
  TextField,
  Paper,
  Typography,
  Button,
} from '@mui/material';
import MicIcon from '@mui/icons-material/Mic';
import SendIcon from '@mui/icons-material/Send';
import StopIcon from '@mui/icons-material/Stop';
import KeyboardIcon from '@mui/icons-material/Keyboard';
import Message from './Message';
import useChatStore from '../store/chatStore';
import { voiceUtils } from '../utils/voiceUtils';
import { AIUtils } from '../utils/aiUtils';

const ChatInterface = () => {
  const messagesEndRef = useRef(null);
  const [inputText, setInputText] = useState('');
  const [volume, setVolume] = useState(0);
  const audioContextRef = useRef(null);
  const analyserRef = useRef(null);
  const animationFrameRef = useRef(null);
  const mediaStreamRef = useRef(null);
  const {
    messages,
    isVoiceMode,
    isRecording,
    currentVoiceText,
    isAIResponding,
    addMessage,
    setVoiceMode,
    setRecording,
    setCurrentVoiceText,
    setAIResponding,
  } = useChatStore();

  const scrollToBottom = () => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  };

  useEffect(() => {
    scrollToBottom();
  }, [messages]);

  // 音律效果相关函数
  const startVisualization = async () => {
    try {
      if (mediaStreamRef.current) {
        mediaStreamRef.current.getTracks().forEach(track => track.stop());
      }
      
      const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
      mediaStreamRef.current = stream;
      
      if (!audioContextRef.current) {
        audioContextRef.current = new (window.AudioContext || window.webkitAudioContext)();
      }
      
      analyserRef.current = audioContextRef.current.createAnalyser();
      const source = audioContextRef.current.createMediaStreamSource(stream);
      source.connect(analyserRef.current);
      analyserRef.current.fftSize = 256;

      const updateVolume = () => {
        if (!analyserRef.current) return;

        const dataArray = new Uint8Array(analyserRef.current.frequencyBinCount);
        analyserRef.current.getByteFrequencyData(dataArray);
        
        // 计算平均音量
        const average = dataArray.reduce((a, b) => a + b) / dataArray.length;
        // 将音量值映射到0-100的范围
        const normalizedVolume = Math.min(100, Math.max(0, (average / 128) * 100));
        
        setVolume(normalizedVolume);
        animationFrameRef.current = requestAnimationFrame(updateVolume);
      };

      updateVolume();
    } catch (error) {
      console.error('启动音频分析失败:', error);
    }
  };

  const stopVisualization = () => {
    if (animationFrameRef.current) {
      cancelAnimationFrame(animationFrameRef.current);
      animationFrameRef.current = null;
    }
    
    if (mediaStreamRef.current) {
      mediaStreamRef.current.getTracks().forEach(track => track.stop());
      mediaStreamRef.current = null;
    }
    
    if (analyserRef.current) {
      analyserRef.current.disconnect();
      analyserRef.current = null;
    }
    
    setVolume(0);
  };

  useEffect(() => {
    if (isRecording && isVoiceMode) {
      startVisualization();
    } else {
      stopVisualization();
    }

    return () => {
      stopVisualization();
    };
  }, [isRecording, isVoiceMode]);

  const handleSendMessage = async () => {
    if (!inputText.trim() || isAIResponding) return;

    const userMessage = {
      content: inputText,
      timestamp: new Date().toISOString(),
      isUser: true,
    };

    addMessage(userMessage);
    setInputText('');
    setAIResponding(true);

    // 添加一个临时的AI消息，用于显示流式输出
    const tempAIMessage = {
      content: '',
      timestamp: new Date().toISOString(),
      isUser: false,
      isStreaming: true,
    };
    addMessage(tempAIMessage);

    // 使用流式输出
    await AIUtils.streamResponse(inputText, (partialText) => {
      // 更新临时消息的内容
      const currentMessages = useChatStore.getState().messages;
      const updatedMessages = [...currentMessages];
      updatedMessages[updatedMessages.length - 1] = {
        ...updatedMessages[updatedMessages.length - 1],
        content: partialText,
      };
      useChatStore.setState({ messages: updatedMessages });
    });

    // 流式输出完成后，移除临时标记
    const currentMessages = useChatStore.getState().messages;
    const finalMessages = [...currentMessages];
    finalMessages[finalMessages.length - 1] = {
      ...finalMessages[finalMessages.length - 1],
      isStreaming: false,
    };
    useChatStore.setState({ messages: finalMessages });
    setAIResponding(false);

    // 如果是语音模式，播放语音
    if (isVoiceMode) {
      voiceUtils.playVoice(finalMessages[finalMessages.length - 1].content);
    }
  };

  const handleStopAI = () => {
    setAIResponding(false);
    // 这里可以添加停止AI回答的逻辑
  };

  const handleVoiceEnd = useCallback(async () => {
    setRecording(false);
    try {
      const audioBlob = await voiceUtils.stopRecording();
      console.log('🚀 ~ handleVoiceEnd ~ audioBlob:', audioBlob);
      
      // 初始化语音识别
      const recognitionSuccess = voiceUtils.initRecognition(
        (text) => {
          console.log('语音识别结果:', text);
          setCurrentVoiceText(text);
        },
        async () => {
          console.log('语音识别完成，最终文本:', currentVoiceText);
          if (currentVoiceText) {
            const userMessage = {
              content: currentVoiceText,
              timestamp: new Date().toISOString(), 
              isUser: true,
            };
            addMessage(userMessage);
            setCurrentVoiceText('');

            // 添加临时AI消息
            const tempAIMessage = {
              content: '',
              timestamp: new Date().toISOString(),
              isUser: false,
              isStreaming: true,
            };
            addMessage(tempAIMessage);

            // 使用流式输出
            await AIUtils.streamResponse(currentVoiceText, (partialText) => {
              const currentMessages = useChatStore.getState().messages;
              const updatedMessages = [...currentMessages];
              updatedMessages[updatedMessages.length - 1] = {
                ...updatedMessages[updatedMessages.length - 1],
                content: partialText,
              };
              useChatStore.setState({ messages: updatedMessages });
            });

            // 流式输出完成后，移除临时标记
            const currentMessages = useChatStore.getState().messages;
            const finalMessages = [...currentMessages];
            finalMessages[finalMessages.length - 1] = {
              ...finalMessages[finalMessages.length - 1],
              isStreaming: false,
            };
            useChatStore.setState({ messages: finalMessages });

            // 播放AI回复语音
            voiceUtils.playVoice(finalMessages[finalMessages.length - 1].content);
          }
        }
      );

      if (!recognitionSuccess) {
        console.error('语音识别初始化失败');
      }
    } catch (error) {
      console.error('停止录音失败:', error);
    }
  }, [addMessage, currentVoiceText, setCurrentVoiceText, setRecording]);

  const handleVoiceModeToggle = useCallback(() => {
    setVoiceMode(!isVoiceMode);
    setInputText(''); // 清空输入框
    if (isRecording) {
      handleVoiceEnd();
    }
  }, [isVoiceMode, isRecording, handleVoiceEnd, setVoiceMode, setInputText]);

  const handleVoiceStart = () => {
    if (!voiceUtils.speechRecognition) {
      alert('您的浏览器不支持语音识别功能，请使用Chrome或Edge浏览器');
      return;
    }

    setRecording(true);
    voiceUtils.startRecording();
    
    const initSuccess = voiceUtils.initRecognition(
      (text) => {
        console.log('实时识别结果:', text);
        setCurrentVoiceText(text);
      },
      async () => {
        console.log('语音识别结束');
        setRecording(false);
        // 如果当前有文本，发送消息
        if (currentVoiceText) {
          const userMessage = {
            content: currentVoiceText,
            timestamp: new Date().toISOString(),
            isUser: true,
          };
          addMessage(userMessage);
          setCurrentVoiceText('');

          // 添加临时AI消息
          const tempAIMessage = {
            content: '',
            timestamp: new Date().toISOString(),
            isUser: false,
            isStreaming: true,
          };
          addMessage(tempAIMessage);

          // 使用流式输出
          await AIUtils.streamResponse(currentVoiceText, (partialText) => {
            const currentMessages = useChatStore.getState().messages;
            const updatedMessages = [...currentMessages];
            updatedMessages[updatedMessages.length - 1] = {
              ...updatedMessages[updatedMessages.length - 1],
              content: partialText,
            };
            useChatStore.setState({ messages: updatedMessages });
          });

          // 流式输出完成后，移除临时标记
          const currentMessages = useChatStore.getState().messages;
          const finalMessages = [...currentMessages];
          finalMessages[finalMessages.length - 1] = {
            ...finalMessages[finalMessages.length - 1],
            isStreaming: false,
          };
          useChatStore.setState({ messages: finalMessages });

          // 播放语音
          voiceUtils.playVoice(finalMessages[finalMessages.length - 1].content);
        }
      }
    );

    if (!initSuccess) {
      setRecording(false);
      alert('语音识别初始化失败，请检查浏览器权限设置');
    }
  };

  return (
    <Box
      sx={{
        height: '100vh',
        display: 'flex',
        flexDirection: 'column',
        bgcolor: 'background.default',
        width: '100%',
        margin: 0,
        padding: 0,
      }}
    >
      {/* 标题栏 */}
      <Paper
        elevation={2}
        sx={{
          p: 2,
          display: 'flex',
          justifyContent: 'center',
          alignItems: 'center',
          width: '100%',
          flexShrink: 0,
          position: 'relative',
          zIndex: 2,
        }}
      >
        <Typography variant="h6">AI智能助手</Typography>
      </Paper>

      {/* 消息区域 */}
      <Box
        sx={{
          flex: 1,
          overflow: 'auto',
          p: 2,
          width: '100%',
          position: 'relative',
          zIndex: 1,
          '&::-webkit-scrollbar': {
            width: '8px',
            height: '8px',
          },
          '&::-webkit-scrollbar-track': {
            background: 'transparent',
          },
          '&::-webkit-scrollbar-thumb': {
            background: 'rgba(0, 0, 0, 0.2)',
            borderRadius: '4px',
            '&:hover': {
              background: 'rgba(0, 0, 0, 0.3)',
            },
          },
          // 支持Firefox
          scrollbarWidth: 'thin',
          scrollbarColor: 'rgba(0, 0, 0, 0.2) transparent',
          // 支持触摸设备
          WebkitOverflowScrolling: 'touch',
          // 优化滚动性能
          willChange: 'scroll-position',
          // 启用硬件加速
          transform: 'translateZ(0)',
        }}
      >
        {messages.map((message, index) => (
          <Message key={index} message={message} isUser={message.isUser} />
        ))}
        {currentVoiceText && (
          <Message
            message={{
              content: currentVoiceText,
              timestamp: new Date().toISOString(),
              isUser: true,
              status: 'sending',
            }}
            isUser
          />
        )}
        <div ref={messagesEndRef} />
      </Box>

      {/* 输入区域 */}
      <Paper
        elevation={3}
        sx={{
          p: 2,
          display: 'flex',
          flexDirection: 'column',
          gap: 1,
          width: '100%',
          flexShrink: 0,
          position: 'relative',
          zIndex: 2,
        }}
      >
        <Box 
          sx={{ 
            display: 'flex', 
            gap: 1, 
            alignItems: 'center', 
            width: '100%',
            transition: 'none',
          }}
        >
          {isVoiceMode ? (
            <>
              <IconButton
                onClick={handleVoiceModeToggle}
                sx={{
                  backgroundColor: 'rgba(0, 0, 0, 0.05)',
                  '&:hover': {
                    backgroundColor: 'rgba(0, 0, 0, 0.1)',
                  },
                  borderRadius: '50%',
                  transition: 'none',
                }}
              >
                <KeyboardIcon />
              </IconButton>
              <Button
                variant="contained"
                color={isRecording ? 'error' : 'primary'}
                onClick={isRecording ? handleVoiceEnd : handleVoiceStart}
                fullWidth
                sx={{
                  position: 'relative',
                  overflow: 'hidden',
                  backgroundColor: isRecording ? 'rgba(0, 0, 0, 0.05)' : 'primary.main',
                  '&:hover': {
                    backgroundColor: isRecording ? 'rgba(0, 0, 0, 0.1)' : 'primary.dark',
                  },
                  transition: 'none',
                  '&::before': isRecording ? {
                    content: '""',
                    position: 'absolute',
                    top: 0,
                    left: 0,
                    width: `${volume}%`,
                    height: '100%',
                    background: `linear-gradient(90deg, 
                      rgba(255, 182, 193, 0.3) 0%, 
                      rgba(255, 218, 185, 0.3) 20%, 
                      rgba(255, 250, 205, 0.3) 40%, 
                      rgba(144, 238, 144, 0.3) 60%, 
                      rgba(173, 216, 230, 0.3) 80%, 
                      rgba(221, 160, 221, 0.3) 100%
                    )`,
                    transition: 'none',
                    zIndex: 1,
                  } : {},
                  '& > span': {
                    position: 'relative',
                    zIndex: 2,
                    color: isRecording ? 'text.primary' : 'white',
                  },
                }}
              >
                {isRecording ? '点击停止' : '点击开始说话'}
              </Button>
            </>
          ) : (
            <>
              <IconButton
                onClick={handleVoiceModeToggle}
                sx={{
                  backgroundColor: 'rgba(0, 0, 0, 0.05)',
                  '&:hover': {
                    backgroundColor: 'rgba(0, 0, 0, 0.1)',
                  },
                  borderRadius: '50%',
                  transition: 'none',
                }}
              >
                <MicIcon />
              </IconButton>
              <TextField
                size="small"
                variant="outlined"
                placeholder="输入消息..."
                value={inputText}
                onChange={(e) => setInputText(e.target.value)}
                onKeyPress={(e) => {
                  if (e.key === 'Enter' && !isAIResponding) {
                    handleSendMessage();
                  }
                }}
                disabled={isAIResponding}
                sx={{
                  flex: 1,
                  '& .MuiOutlinedInput-root': {
                    borderRadius: '20px',
                  },
                  transition: 'none',
                }}
              />
              <IconButton
                onClick={isAIResponding ? handleStopAI : handleSendMessage}
                disabled={!inputText.trim() && !isAIResponding}
                sx={{
                  backgroundColor: isAIResponding ? 'error.main' : 'primary.main',
                  color: 'white',
                  '&:hover': {
                    backgroundColor: isAIResponding ? 'error.dark' : 'primary.dark',
                  },
                  '&.Mui-disabled': {
                    backgroundColor: 'rgba(0, 0, 0, 0.12)',
                    color: 'rgba(0, 0, 0, 0.26)',
                  },
                  borderRadius: '50%',
                  transition: 'none',
                }}
              >
                {isAIResponding ? <StopIcon /> : <SendIcon />}
              </IconButton>
            </>
          )}
        </Box>
      </Paper>
    </Box>
  );
};

export default ChatInterface; 